package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.mapper.ActivityMapper;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.service.ActivityService;
import com.example.demo.service.GoodsService;
import com.example.demo.service.PrizeService;

import com.github.pagehelper.PageInfo;
import com.tencentcloudapi.mrs.v20200910.models.Organ;
import com.tencentcloudapi.organization.v20181225.OrganizationErrorCode;
import io.swagger.annotations.*;
import io.swagger.models.auth.In;
import lombok.Builder;
import lombok.SneakyThrows;
import org.aspectj.weaver.ast.Or;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Api(tags="活动管理接口")
@RestController
@RequestMapping("/organizer")
//@CrossOrigin(origins = "*")
public class OrganizerController {
    @Resource
    private ActivityService activityService;
    @Resource
    private PrizeService prizeService;
    @Resource
    private GoodsService goodsService;
    //testOK
    //添加活动
//    //@PreAuthorize("hasRole('admin')")
    //@PreAuthorize("hasAuthority('sys:activity:add')")
    @ApiOperation(value="添加活动")
    @ApiResponses(value={
            @ApiResponse(code=200, message="添加活动成功"),
            @ApiResponse(code=401, message="添加活动失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping("/addActivity")
    public Result addActivity(@RequestBody Activity activity){
        int res=activityService.addActivity(activity);
        if(res==1){
            return Result.success(activity);
        }else{
            return Result.error("401","添加活动失败");
        }
    }

    @Resource
    private ActivityMapper activityMapper;
    //testOK
    //获取所有活动
//    //@PreAuthorize("hasAuthority('sys:activity:get')")
    @SneakyThrows
    @ApiOperation(value="获取活动列表", notes="根据活动名称、每页数量和当前页码获取活动列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", value = "每页数量", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码", required = true, dataType = "int", paramType = "query")
    })
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取活动列表成功"),
            @ApiResponse(code=400, message="获取活动列表失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/getActivities")
    public PageInfo<Activity> getActivities(String activityName, String startTime, String endTime,
                                                           @RequestParam(defaultValue = "1") int current,
                                                           @RequestParam(defaultValue = "10") int size){
        List<Activity> activityList = new ArrayList<>();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        if(startTime != null && !startTime.isEmpty()){
            startDate = formatter.parse(startTime);
        }
        if(endTime != null && !endTime.isEmpty()){
            endDate = formatter.parse(endTime);
        }
        activityList = activityMapper.getActivitySearch(activityName,startDate,endDate);
        List<Activity> pageList = activityList.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<Activity> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = activityList.size();
        pageInfo.setTotal(total);
        return pageInfo;




    }
    //testOK
    //删除活动
//    //@PreAuthorize("hasRole('admin')")
    //@PreAuthorize("hasAuthority('sys:activity:del')")
    @ApiOperation(value="删除活动", notes="根据活动ID列表批量进行活动删除")
    @ApiImplicitParam(name = "activityId", value = "活动ID列表", required = true, dataType = "MyArray", paramType = "body")
    @ApiResponses(value={
            @ApiResponse(code=200, message="删除成功"),
            @ApiResponse(code=500, message="删除失败"),

    })
    @PostMapping("/delActivity")
    public Result delActivity(@RequestBody MyArray activityId){
        int res=activityService.delActivity(activityId);
        if(res==1){
            return Result.success("删除成功");
        }else{
            return Result.error("500","删除失败");
        }
    }

    //更新活动信息
//    //@PreAuthorize("hasRole('admin')")

    //testOK
    //@PreAuthorize("hasAuthority('sys:activity:edit')")
    @ApiOperation(value="更新活动信息")
    @ApiResponses(value={
            @ApiResponse(code=200, message="更新成功"),
            @ApiResponse(code=403, message="未能成功更新活动信息"),
    })
    @PutMapping("/updateActivity")
    public Result updateActivity(@RequestBody Activity activity){
        int res=activityService.updateActivity(activity);
        if(res==1){
            return Result.success(activity);
        }else{
            return Result.error("403","未能成功更新活动信息");
        }
    }

    //testOK
    //通过活动ID获取活动信息
    //@PreAuthorize("hasAuthority('sys:activity:get')")
    @ApiOperation(value="获取活动信息", notes="根据活动ID获取活动信息")
    @ApiImplicitParam(name = "activityId", value = "活动ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取成功"),
            @ApiResponse(code=500, message="未能获取活动信息"),

    })
    @GetMapping("/getActivityById")
    public Result getActivityById(Integer activityId){
        Activity res=activityService.selectActivityById(activityId);
        if(res!=null){
            return Result.success(res);
        }else{
            return Result.error("500","未能获取活动信息");
        }
    }

    //testOK
//    //@PreAuthorize("hasAuthority('sys:prize:get')")
    @ApiOperation(value = "通过活动ID获取奖品列表", notes = "根据传入的活动ID获取该活动下的所有奖品列表")
    @ApiImplicitParam(name = "activityId", value = "活动ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 404, message = "请求路径不存在"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("/getPrizeByActivityId")
    public Result getPrizeByActivityId(Integer activityId){
        List<PrizesInActivities> res=prizeService.getPrizeByActivityId(activityId);
        return Result.success(res);
    }

    //testOK
    //@PreAuthorize("hasAuthority('sys:prize:add')")
    @ApiOperation(value = "添加奖品", notes = "在指定活动下添加奖品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodId", value = "奖品ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodProbability", value = "中奖概率", required = true, dataType = "Float", paramType = "query")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "添加成功"),
            @ApiResponse(code = 500, message = "添加失败")
    })
    @PostMapping("/addPrize")
    public Result addPrize(@RequestBody List<Goods> goods, Integer activityId,Float goodProbability){
        if(goodProbability==null){
            for(Goods goods1 : goods){
                prizeService.addPrize(activityId, goods1.getGoodId(), 0f);
            }
        }else{
            for(Goods goods1 : goods){
                prizeService.addPrize(activityId, goods1.getGoodId(), goodProbability);
            }
        }

        return Result.success("添加成功");
    }

    @ApiOperation(value="修改奖品概率", notes="根据商家id获取未发货奖品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodId", value = "商品id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "goodProbability", value = "概率", dataType = "float", paramType = "query")
    })
    @PutMapping("/editProbability")
    public Result editProbability(Integer activityId, Integer goodId, Float goodProbability){
        Integer res = prizeService.editProbability(activityId, goodId, goodProbability);
        if(res == 1){
            return Result.success("修改成功");
        }else {
            return Result.error("500","修改失败");
        }
    }

    //testOK
    //@PreAuthorize("hasAuthority('sys:prize:del')")
    @ApiOperation(value="删除奖品", notes="根据奖品ID列表批量进行奖品删除")
    @ApiImplicitParam(name = "prizes", value = "奖品ID列表", required = true, dataType = "MyArray", paramType = "body")
    @ApiResponses(value={
            @ApiResponse(code=200, message="删除成功"),
            @ApiResponse(code=500, message="删除失败"),
    })
    @PostMapping("delPrize")
    public Result delPrize(@RequestBody MyArray prizes){
        int res=prizeService.delPrize(prizes);
        if(res==1){
            return Result.success("删除成功");
        }else{
            return Result.error("403","删除失败");
        }
    }


    @ApiOperation(value = "获取商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commodityName", value = "商品名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "minPrice", value = "最小价格", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "maxPrice", value = "最大价格", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页数量", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页数", dataType = "int", paramType = "query")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "服务器错误")
    })
    @GetMapping("getCommodities")
    public PageInfo<OrganizerGoods> getCommodities(String commodityName, String minPrice, String maxPrice, String businessName,
                                          @RequestParam(defaultValue = "1") int current,
                                          @RequestParam(defaultValue = "10") int size){
        List<OrganizerGoods> goodsList = goodsService.getCommodities();

        if(businessName.isEmpty() && maxPrice.isEmpty() && minPrice.isEmpty() && commodityName.isEmpty()){
            List<OrganizerGoods> pageList = goodsList.stream()
                    .skip((current - 1) * size) // 跳过前面的记录
                    .limit(size) // 取出指定数量的记录
                    .collect(Collectors.toList()); // 将结果转换为列表
            PageInfo<OrganizerGoods> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
            long total = goodsList.size();
            pageInfo. setTotal(total);
            return pageInfo;
        }

        Predicate<OrganizerGoods> predicate0 = null;
        Predicate<OrganizerGoods> predicate1 = null;
        Predicate<OrganizerGoods> predicate2 = null;
        Predicate<OrganizerGoods> predicate3 = null;
        if(!commodityName.isEmpty()) {
            current = 1;
            predicate0 = organizerGoods -> organizerGoods.getGoods().getGoodName().contains(commodityName);
        }
        if(!minPrice.isEmpty()){
            current = 1;
            predicate1 = organizerGoods -> organizerGoods.getGoods().getGoodPrice() >= Integer.parseInt(minPrice);
        }
        if(!maxPrice.isEmpty()) {
            current = 1;
            predicate2 = organizerGoods -> organizerGoods.getGoods().getGoodPrice() <= Integer.parseInt(maxPrice);
        }
        if(!businessName.isEmpty()){
            current = 1;
            predicate3 = organizerGoods -> organizerGoods.getBusinessName().contains(businessName);
        }

        Predicate<OrganizerGoods> predicate = null;
        //1111
        if(predicate0 != null && predicate1 != null && predicate2 != null && predicate3 != null){
            predicate = predicate0.and(predicate1).and(predicate2).and(predicate3);
        }//1011
        else if(predicate0 != null && predicate1 == null && predicate2 != null && predicate3 != null){
            predicate = predicate0.and(predicate2).and(predicate3);
        }//1001
        else if(predicate0 != null && predicate1 == null && predicate2 == null && predicate3 != null){
            predicate = predicate0.and(predicate3);
        }//1000
        else if(predicate0 != null && predicate1 == null && predicate2 == null && predicate3 == null){
            predicate = predicate0;
        }//1101
        else if(predicate0 != null && predicate1 != null && predicate2 == null && predicate3 != null){
            predicate = predicate0.and(predicate1).and(predicate3);
        }//1010
        else if(predicate0 != null && predicate1 == null && predicate2 != null && predicate3 == null){
            predicate = predicate0.and(predicate2);
        }//1100
        else if(predicate0 != null && predicate1 != null && predicate2 == null && predicate3 == null){
            predicate = predicate0.and(predicate1);
        }//1110
        else if(predicate0 != null && predicate1 != null && predicate2 != null && predicate3 == null){
            predicate = predicate0.and(predicate1).and(predicate2);
        }//0111
        else if(predicate0 == null && predicate1 != null && predicate2 != null && predicate3 != null){
            predicate = predicate1.and(predicate2).and(predicate3);
        }//0011
        else if(predicate0 == null && predicate1 == null && predicate2 != null && predicate3 != null){
            predicate = predicate2.and(predicate3);
        }//0001
        else if(predicate0 == null && predicate1 == null && predicate2 == null && predicate3 != null){
            predicate = predicate3;
        }//0110
        else if(predicate0 == null && predicate1 != null && predicate2 != null && predicate3 == null){
            predicate = predicate1.and(predicate2);
        }//0010
        else if(predicate0 == null && predicate1 == null && predicate2 != null && predicate3 == null){
            predicate = predicate2;
        }//0100
        else if(predicate0 == null && predicate1 != null && predicate2 == null && predicate3 == null){
            predicate = predicate1;
        }
        List<OrganizerGoods> result = goodsList.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        List<OrganizerGoods> pageList = result.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<OrganizerGoods> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = result.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }

    @ApiOperation(value="获取未被当前活动添加的商品列表", notes="获取未被当前活动添加的商品列表")
    @ApiImplicitParam(name = "activityId", value = "活动id", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取成功"),
            @ApiResponse(code=500, message="获取失败"),
    })
    @GetMapping("/getCommoditiesUnChoose")
    public Result getCommoditiesUnChoose(Integer activityId){
        List<OrganizerGoods> result = goodsService.getCommoditiesUnChoose(activityId);
        if(!result.isEmpty()){
            return Result.success(result);
        }else {
            return Result.error("403","获取失败");
        }
    }
}
